package org.sparkle.observer;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import org.sparkle.ioc.Bean;
import org.sparkle.ioc.ServiceLookup;
import org.sparkle.register.RegisterFactory;

public class ObserverFactory {

	private ObRegister register;
	private static ObserverFactory instance;
	
	public void fireEvent(ObEvent event){
		List<Method> methods=getRegister().getMethods().get(event);
		
		if(methods!=null){
			for(Method m: methods){
				try {
					
					Bean ann=m.getDeclaringClass().getAnnotation(Bean.class);
					
					Object obj=ServiceLookup.getInstance().get(ann.value());
					
					m.invoke(obj, event);
					
				} catch (IllegalAccessException
						| IllegalArgumentException
						| InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	protected ObRegister getRegister(){
		if(register==null)
			register=(ObRegister) RegisterFactory.getInstance().getRegisterByName("ObRegister");
		return register;
	}

	public static ObserverFactory getInstance() {
		if(instance==null)
			instance=new ObserverFactory();
		return instance;
	}
	
}
